﻿namespace ZyGame.Event
{
    using System;
    using System.Collections.Generic;

    sealed class GameEventDispatcher : IEventHandle
    {
        private Dictionary<string, GameEventHandler> handles = new Dictionary<string, GameEventHandler>();

        public void Notify(string evtName, object evtData)
        {
            if (!handles.TryGetValue(evtName, out GameEventHandler handler))
            {
                return;
            }

            handler.OnTigger(evtData);
        }

        public void Register(string eventName, bool isOnce, Action<object> callback)
        {
            if (!handles.TryGetValue(eventName, out GameEventHandler handler))
            {
                handles.Add(eventName, handler = new GameEventHandler());
            }

            handler.Add(callback, isOnce);
        }

        public void Unregister(string eventName, Action<object> callback)
        {
            if (!handles.TryGetValue(eventName, out GameEventHandler handler))
            {
                return;
            }

            handler.Remove(callback);
        }

        public void Clear(string evtName)
        {
            if (evtName.IsNullOrEmpty())
            {
                handles.Clear();
                return;
            }

            if (handles.ContainsKey(evtName))
            {
                handles.Remove(evtName);
            }
        }

        public void Dispose()
        {
            Clear(string.Empty);
        }
    }
}